package com.qire.manhua.dal.service;

import com.qire.antsbinder.dal.DataService;
import com.qire.antsbinder.dal.annotation.StrategyAnnotation;
import com.qire.antsrouter.lifecycleHandler.ActivityManageHandler;
import com.qire.common.basic.ObjectUtil;
import com.qire.common.constant.CustomEvent;
import com.qire.common.constant.Url;
import com.qire.common.dal.WarehouseFactory;
import com.qire.common.dal.base.MD5;
import com.qire.common.model.entity.UserEntity;
import com.qire.common.model.enumeration.LoginChannelType;
import com.qire.common.support.CustomLoadDialog;
import com.qire.common.support.base.BaseActivity;
import com.qire.common.utils.NoticeEventBus;

import com.qire.common.utils.ScheduledTaskHelper;
import com.qire.common.utils.ToastHelper;
import com.qire.common.widget.snackbar.Prompt;
import com.qire.manhua.dal.IUserDataDAL;
import com.qire.manhua.dialog.NewcomerGuideRewardDialog;
import com.qire.manhua.model.viewModel.impl.LoginGuideViewModel;
import com.qire.manhua.model.vo.LoginRespVO;
import com.qire.manhua.model.vo.MobileAuthInfoVO;
import com.qire.manhua.model.vo.OkResponseVO;
import com.qire.manhua.model.vo.UserDetailVO;
import com.qire.other.thirdPlatform.QqPlatform;
import com.qire.other.thirdPlatform.WeChatPlatform;

import androidx.lifecycle.Lifecycle;

/**
 * 登录页数据服务
 */
public class LoginGuideService extends DataService {

    private final LoginGuideViewModel viewModel;
    private final IUserDataDAL userDataDAL = WarehouseFactory.create(this, IUserDataDAL.class);

    public LoginGuideService(LoginGuideViewModel viewModel) {
        this.viewModel = viewModel;
    }

    /**
     * 手机号码验证，是否存在
     */
    public void phoneAuth() {
        userDataDAL.fetchMobileAuthInfo(viewModel.phoneNumber());
    }
    @StrategyAnnotation(event = Url.v5_mobileAuthInfo)
    public void mobileAuthInfoApiCallbackRefresh(MobileAuthInfoVO dataVO, boolean isCache) {
        viewModel.updateMobileAuthInfo(dataVO.is_reg == 0, dataVO.is_pwd == 0, dataVO.is_name == 0);
    }

    /**
     * 获取验证码
     */
    public void fetchVerificationCode() {
        userDataDAL.fetchVerificationCode(viewModel.phoneNumber());
    }
    @StrategyAnnotation(event = Url.FetchVerificationCode)
    public void fetchVerificationCodeCallback(OkResponseVO okResponseVO, boolean isCache) {
        ToastHelper.showSnackBar("验证码已发送请注意查收！", Prompt.SUCCESS);
    }

    /**
     * 校验验证码
     * @param verifyCode 验证码
     */
    public void checkVerificationCode(String verifyCode) {
        userDataDAL.checkVerificationCode(viewModel.phoneNumber(), verifyCode);
    }
    @StrategyAnnotation(event = Url.CheckVerificationCode)
    public void checkVerificationCodeCallback(OkResponseVO okResponseVO, boolean isCache) {
//        ToastHelper.showSnackBar("验证成功！", Prompt.SUCCESS);
        viewModel.setValidateCode(okResponseVO.validate);
        viewModel.switchPage();
    }

    /**
     * 手机注册
     * @param activitySimpleName 页面名称
     */
    public void phoneRegister(String activitySimpleName) {
        userDataDAL.registerAccountByPhone(viewModel.phoneNumber(), viewModel.registerPassword(), activitySimpleName);
    }
    @StrategyAnnotation(event = Url.RegisterAccount)
    public void registerAccountApiCallbackRefresh(LoginRespVO loginRespVO, boolean isCache) {
        //注册API调用后回调处理
        loginAction(loginRespVO);
        viewModel.switchPage();
    }

    /**
     * 手机号登录
     * @param activitySimpleName 操作发生的页面名称
     */
    public void mobileLogin(String activitySimpleName) {
        userDataDAL.requestMobileLogin(viewModel.phoneNumber(), viewModel.loginPassword(), activitySimpleName);
        UserEntity.self.setLoginChannel(LoginChannelType.PHONE);
        UserEntity.self.save();
    }
    /**
     * 微信登录
     * @param activitySimpleName 操作发生的页面名称
     */
    public void weChatLogin(final String activitySimpleName) {
        WeChatPlatform.WeChat.authorize((msg, info) -> {
            if(ObjectUtil.nonNull(info)) {
                // 微信的用户性别 1:男，2:女。奇热平台的 1:男 0:女。所以需要一个简单的转换
                int userSex = ObjectUtil.equals(info.sex, "1") ? 1 : 0;
                userDataDAL.requestWeChatLogin(info.openid, info.nickname, info.headimgurl, userSex, info.unionid, activitySimpleName);
                UserEntity.self.setLoginChannel(LoginChannelType.WeChat);
                UserEntity.self.save();
            } else {
                ToastHelper.showToast(msg);
            }
            CustomLoadDialog.dismissDialog();
        });
    }
    /**
     * qq登录
     * @param activitySimpleName 操作发生的页面名称
     */
    public void qqLogin(final String activitySimpleName) {
        QqPlatform.build().authorize((msg, info) -> {
            if(ObjectUtil.nonNull(info)) {
                // 微信的用户性别 1:男，2:女。奇热平台的 1:男 0:女。所以需要一个简单的转换
                int userSex = ObjectUtil.equals(info.sex, "1") ? 1 : 0;
                userDataDAL.requestQqLogin(info.openid, info.nickname, info.headimgurl, userSex, activitySimpleName);
                UserEntity.self.setLoginChannel(LoginChannelType.QQ);
                UserEntity.self.save();
            } else {
                ToastHelper.showToast(msg);
            }
            CustomLoadDialog.dismissDialog();
        });
    }
    @StrategyAnnotation(event = {Url.QqLogin, Url.WeChatLogin, Url.MobileLogin})
    public void requestLoginApiCallbackRefresh(LoginRespVO loginRespVO, boolean isCache) {
        loginAction(loginRespVO);
        viewModel.switchPage();
    }

    public void updateNickname() {
        userDataDAL.updateNickname(viewModel.nickname());
    }
    @StrategyAnnotation(event = Url.v5_nicknameUpdate)
    public void nicknameUpdateApiCallbackRefresh(OkResponseVO okResponseVO, boolean isCache) {
        //修改昵称API调用后回调处理
        if(okResponseVO.isOK()) {
            ToastHelper.showSnackBar("昵称修改成功！", Prompt.SUCCESS);
            NoticeEventBus.NOTICE.sendEvent(CustomEvent.USER_UPDATE_REFRESH);
        } else {
            ToastHelper.showSnackBar("昵称修改失败！", Prompt.ERROR);
        }
    }

    public void retrievePasswordAction(String validateCode) {
        String password = MD5.Md5(viewModel.newPassword());
        userDataDAL.updatePassword(viewModel.phoneNumber(), password, password, validateCode, "msgcode");
    }
    public void updatePasswordAction(String validateCode) {
        String password = MD5.Md5(viewModel.changePassword());
        userDataDAL.updatePassword(viewModel.phoneNumber(), password, password, validateCode, "msgcode");
    }
    @StrategyAnnotation(event = Url.UpdatePassword)
    public void updatePasswordCallback(OkResponseVO okResponseVO, boolean isCache) {
        //修改密码API调用后回调处理
        if(okResponseVO.isOK()) {
            ToastHelper.showSnackBar("密码修改成功！", Prompt.SUCCESS);
            viewModel.switchPage();
        } else {
            ToastHelper.showSnackBar("密码修改失败！", Prompt.ERROR);
        }
    }

    public void requestMyUserData() {
        userDataDAL.refreshUserDetailData();
        new TeensModeService().queryTeensModeState();
    }
    @StrategyAnnotation(event = Url.myIndex)
    public void refreshUserDetailDataCallback(UserDetailVO dataVO, boolean isCache) {
        if(isCache || dataVO == null) {
            return;
        }
        dataVO.updateUserEntity();
    }

    /**
     * 登录行为
     * */
    private void loginAction(LoginRespVO loginRespVO) {
        // 登录
        UserEntity.self.login(loginRespVO.userid, loginRespVO.token);

//        // 检查有没有免费的vip待领取
//        requestHaveFreeVIP();

        // 登录成功广播通知
        NoticeEventBus.NOTICE.sendEvent(CustomEvent.LOGIN_SUCCESS);

        // 登录完成刷新用户本地信息
        requestMyUserData();


        // 提示登录成功顶部样式气泡
        ToastHelper.showSnackBar("登录成功", Prompt.SUCCESS);

        // 检查是否存在新人福利，及福利是否有效
        if(ObjectUtil.nonNull(loginRespVO.welfare) && loginRespVO.welfare.nua_num > 0) {
            // 获得登录页上一个页面，用于投放dialog
            BaseActivity previousActivity = (BaseActivity) ActivityManageHandler.HANDLER.previousActivity();
            if (ObjectUtil.nonNull(previousActivity)) {
                // 制定一个计划任务，投放在登录页退出后的上一个页面，条件在生命周期 RESUMED 后执行， 计划任务为show dialog
                new ScheduledTaskHelper(previousActivity.getLifecycle())
                        .buildTask(loginRespVO) // 传递的数据 data
                        .setConditional(Lifecycle.State.RESUMED) // 条件
                        .setTask(data -> { // 任务内容
                            NewcomerGuideRewardDialog dialog = new NewcomerGuideRewardDialog(previousActivity);
                            if ("bean".equals(data.welfare.nua_type)) {
                                dialog.setBeanReward(data.welfare.nua_num + "金豆");
                            } else {
                                dialog.setVipReward(data.welfare.nua_num + "天会员");
                            }
                            dialog.show();
                            return true;
                        }).submitAndDoTask();//提交并执行，如果达成条件会立刻执行，如果未达到，则会在条件达到时执行
            }
        }
    }

}
